package fengstyle.algorithm;

import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.util.*;

public class MyRangeAlgotithm implements RangeShardingAlgorithm<String> {

    /**
     * 自定义范围分表算法
     * @param tableNames
     * @param shardingValue
     * @return
     */
    @Override
    public Collection<String> doSharding(Collection<String> tableNames, RangeShardingValue<String> shardingValue) {

        String lower = shardingValue.getValueRange().lowerEndpoint();
        String upper = shardingValue.getValueRange().upperEndpoint();
        int l = Integer.valueOf(lower.substring(0,4));
        int r = Integer.valueOf(upper.substring(0,4));
        Set<String> result = new LinkedHashSet<>();
        for(String tableName : tableNames){
            System.out.println(tableName);
            int year = Integer.valueOf(tableName.substring(tableName.length() - 4, tableName.length()));
            if(year >= l && year <= r){
                result.add(tableName);
            }
        }
        return result;
    }
}
